<template>
  <el-card class="box-card">
    <itable
    :table="tconfig.tableConfig"
    :tableData="tconfig.tableData"
    :page-bean="tconfig.pageBean"
    @pageChange="pageChange"
    @handleInfo="handleInfo"
    @handleEdit="handleEdit"
    @handleDel="handleDel"
    >
      <template #searchBox>
        <Eform
          :model="form"
          :elem="fromData"
          :submit="true"
          :reset="true"
          :button="false"
          okIcon="Search"
          btnSize="default"
          submitText="搜索"
          @onSuccess="onSuccess"
          @onReset="onReset"
          >
        </Eform>
      </template>
      <template #sort="prop">
        <el-input-number v-model="prop.obj.row.sort" :min="0"  @change="handleChange(prop.obj.row)"/>
      </template>
      <template #headerbtn>
        <div style="display: flex;">
          <el-button type="primary" plain @click="clickadd" icon="Plus">添加</el-button>
          <el-button type="primary" plain @click="importTemplate">导入模板下载</el-button>
          <upfile @upload-success="allimport" btntext="批量导入" ref="fileRef"/>
        </div>
      </template>
    </itable>

    <el-drawer
    :title="title == 0?'查看':title == 1?'编辑':'新增'"
    :before-close="handleClose"
    v-model="dialogVisible"
    size="30%">
    <Eform
        :model="dform"
        :rules="drules"
        :elem="dfromData"
        btnSize="large"
        :inline="false"
        :submit="false"
        :reset="false"
        :button="false"
        ref="ruleFormRef"
        labelPosition="left"
      >
    </Eform>
    <template #footer>
      <span class="dialog-footer">
        <template v-if="title == 1 || title == 2">
          <el-button @click="clickCancel">取 消</el-button>
          <el-button type="primary" @click="clickComfig">保 存</el-button>
        </template>
        <template v-else>
          <el-button type="primary" @click="clickStaffEdit">编辑员工</el-button>
        </template>
      </span>
  </template>
  </el-drawer>
  </el-card>
</template>

<script setup lang='ts'>
import { reactive, ref } from 'vue';
import { PageBean } from "@/utils/page-bean";
import { useRouter } from 'vue-router';
import { useStore } from 'vuex'
import itable from '@/components/table/table.vue'
import Eform from '@/components/eform/index.vue';
import useCurrentInstance from '@/utils/useCurrentInstance';
import { ElMessageBox } from 'element-plus'
import upfile from '@/components/upfile.vue';
import { setTabs, getTabs } from '@/utils/storage.js'

const { proxy } = useCurrentInstance()
const store = useStore()
const router = useRouter()
let title = ref(0)
let ruleFormRef = ref()
let dialogVisible = ref(false)
let fromData = reactive([
  {
    label: "员工姓名",
    prop: "name",
    clearable: true,
  },
  {
    label: "联系方式",
    prop: "phone",
    clearable: true,
  }
])
let form = reactive({
  name:'',
  phone:'',
  page:1,
  size:10
})
let dfromData = reactive([
  {
    label: "员工名称",
    prop: "name",
    labelWidth:'100px',
    size:'large',
    clearable: true,
    disabled:false,
    style:{paddingBottom:'18px'},
  },
  {
    label: "联系方式",
    prop: "phone",
    labelWidth:'100px',
    size:'large',
    clearable: true,
    disabled:false,
    style:{paddingBottom:'18px'},
  },
  {
    label: "身份证号",
    prop: "id_card",
    labelWidth:'100px',
    size:'large',
    clearable: true,
    disabled:false,
    style:{paddingBottom:'18px'},
  },
  {
    label: "职位工作",
    prop: "company_position_id",
    labelWidth:'100px',
    element:'select',
    option:[],
    optlabel:'name',
    optvalue:'id',
    size:'large',
    remark:'请慎重更换职位工作，新的职位工作将在明天开始生效。新职位生效前，此处还会显示之前的职位。',
    clearable: true,
    disabled:false,
    elemStyle:{width:'100%'},
    style:{paddingBottom:'15px'},
  },
  {
    label: "所在小组",
    prop: "company_group_id",
    labelWidth:'100px',
    element:'select',
    option:[],
    optlabel:'name',
    optvalue:'id',
    size:'large',
    clearable: true,
    disabled:false,
    elemStyle:{width:'100%'},
    style:{paddingBottom:'18px'},
  },
  {
    label: "排序",
    prop: "sort",
    labelWidth:'100px',
    element:'number',
    size:'large',
    clearable: true,
    disabled:false,
    style:{paddingBottom:'18px'},
  },
  {
    label: "小组角色",
    prop: "company_group_type",
    element:'radio',
    option:[
      { value:1, label:'组长' },
      { value:2, label:'组员' },
    ],
    labelWidth:'100px',
    size:'large',
    clearable: true,
    disabled:false,
  }
])
let drules = reactive({
  name:[
    { required: true, message: '请输入员工名称', trigger: 'blur' },
  ],
  phone:[
    { required: true, message: '请输入联系方式', trigger: 'blur' },
  ],
  id_card:[
    { required: true, message: '请填写身份证号', trigger: 'blur' },
    { pattern:/(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/, message: '请输入正确的证件号', trigger: 'blur' },
  ],
  company_position_id:[
    { required: true, message: '请选择职位', trigger: 'change' },
  ],
  company_group_id:[
    { required: false, message: '请选择所在小组', trigger: 'change' },
  ],
})
let dform = reactive({
  name:'',
  phone:'',
  sort:0,
  company_position_id:'',
  id_card:'',
  company_group_type:2,
  company_group_id:''
})
const tconfig = reactive({
  tableConfig: {} as {loading:boolean,[propName:string]:any},
  tableData: [] as any[],
  pageBean: new PageBean(10, 1, 0),
})

// 重置
const onReset = () => {
  tconfig.pageBean.pageIndex = 1
  getStaffList()
}
// 搜索
const onSuccess = () => {
  tconfig.pageBean.pageIndex = 1
  getStaffList()
}

// 导入模板
const fileRef = ref()
const importTemplate = () => {
  proxy.$api.getCommonConfig().then(async(res) => {
  if(res.code == 200){
    let response = await fetch(res.result.staff_excel_url);
    let blob = await response.blob();
    let objectUrl = window.URL.createObjectURL(blob);
    let a = document.createElement('a');
    a.href = objectUrl;
    a.download = '员工导入模板'
    a.click()
    a.remove();
  }
})
}
// 批量导入
const allimport = (src) => {
  proxy.$api.getStaffImport({url: src }).then(res => {
    if(res.code == 200){
      proxy.$message({
        type:'success',
        message:'导入成功'
      })
      tconfig.pageBean.pageIndex = 1
      getStaffList()
    }
  })
  fileRef.value.clearFiles()
}

// 抽屉-提交
const clickComfig = () => {
  ruleFormRef.value.validate().then(res => {
    if(res){
      if(!dform.company_group_id){
        dform.company_group_id = 0
      }
      if(title.value == 1){
        // 编辑
        proxy.$api.getStaffUpdate(dform).then(res => {
          if(res.code == 200){
            proxy.$message({
              message: res.msg,
              type: 'success'
            })
            getStaffList()
          }
        })
      }
      if(title.value == 2){
        // 新增
        proxy.$api.getStaffCreate(dform).then(res => {
            if(res.code == 200){
              proxy.$message({
                message: res.msg,
                type: 'success'
              })
              getStaffList()
            }
        })
      }
      ruleFormRef.value.concel()
      dialogVisible.value = false
    }
  })
}
// 抽屉-取消
const clickCancel = () => {
  ruleFormRef.value.concel()
  dialogVisible.value = false
}
const handleClose = () => {
  if(ruleFormRef.value) ruleFormRef.value.concel()
  dialogVisible.value = false
}
// 新增员工
const clickadd = () => {
  dfromData.map(item => {
    item.disabled = false
  })
  title.value = 2
  dialogVisible.value = true
}
// 查看-编辑员工
const clickStaffEdit = () => {
  let tab = getTabs()
  let flag = false
  tab.map(item => {
    if(item.id != '1-0-2'){
      flag = true
    }
  })
  if(flag) {
    tab.push({
      id: '1-0-2',
      name: '员工小组',
      path: 'staffGroup',
      active: true
    })
  }
  setTabs(tab,'1-0-2')
  store.commit('getActiveMenu', '1-0-2')
  router.push({path:'/staffGroup'})
}
// 表格-查看
const handleInfo = (a, b, id) => {
  setInfo(b.id)
  dfromData.map(item => {
    item.disabled=true
  })
  title.value = 0
  dialogVisible.value = true
}
// 表格-修改
const handleEdit = (a, b, id) => {
  title.value = 1
  setInfo(b.id,b.sort)
  dfromData.map(item => {
    item.disabled=false
  })
  dialogVisible.value = true
}
const setInfo = (id,sort) => {
  proxy.$api.getStaffDetails({id:id}).then(res => {
    for(let key in dform){
      dform[key] = res.result[key]
    }
    dform.sort = sort
    dform.id = res.result.id
    if(!dform.company_group_id){
      dform.company_group_id = ''
    }
    if(!dform.company_position_id){
      dform.company_position_id = ''
    }
  })
}
// 表格-删除
const handleDel = (a, b, id) => {
    ElMessageBox.confirm(
    '此操作将永久删除该数据,是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    proxy.$api.getStaffDelete({id:b.id}).then(res => {
        if(res.code == 200){
          proxy.$message({
            type: 'success',
            message: res.msg,
          })
          getStaffList()
        }
      })
    })
    .catch(() => {
      proxy.$message({
        type: 'info',
        message: '已取消删除',
      })
    })
}

// 分页
const pageChange = () => {
  getStaffList()
}

// 员工列表
const getStaffList = () => {
  tconfig.tableConfig.loading = true
  form.page = tconfig.pageBean.pageIndex
  proxy.$api.getStaffLists(form).then(res => {
    tconfig.tableData = res.result.lists
    tconfig.pageBean.Total = res.result.total_rows
    tconfig.tableConfig.loading = false
  }).catch(err => {
    tconfig.tableConfig.loading = false
  })
}
getStaffList()
// 员工小组
const getformLists = () => {
  proxy.$api.getGroupLists({page:1,size:9999,name:'',leader:''}).then(res => {
    dfromData[4].option = res.result.lists
  })
  proxy.$api.getPositionSelect({select_type:'1'}).then(res => {
    dfromData[3].option = res.result
  })
}
getformLists()
// 排序
const handleChange = (item) => {
  proxy.$api.getStaffRank({id:item.id,sort:item.sort})
  getStaffList()
}
// 初始化表格
const initTable = () => {
tconfig.tableConfig = {
  loading: true,
  hasSelect: false,
  hasIndex: true,
  hasOperation: true,
  hasSearch: true,
  hasPage: true,
  headerShowBtn:true,
  tr: [
    {
      label: "员工姓名",
      prop: "name",
    },
    {
      label: "联系方式",
      prop: "phone",
    },
    {
      label: "岗位",
      prop: "position",
    },
    {
      label: "排序",
      prop: "sort",
      width:220,
      show:'template'
    },
    {
      label: "所在小组",
      prop: "group",
    }
  ],
  operation:{
    label:'操作',
    width:'300',
    data:[
      { label:'查看', type:'', icon:'Search', Fun:'handleInfo', id: 0 },
      { label:'编辑', type:'', icon:'EditPen', Fun:'handleEdit', id: 1 },
      { label:'删除', type:'danger',icon:'Delete', Fun:'handleDel', id: 2 },
    ]
  }
}
}
initTable()
</script>

<style lang='scss' scoped>
:deep(.el-dialog__body){
.el-form>.el-form-item{
  width: 45%;
  padding-bottom: 20px;
  margin-left: 10px;
}
.el-select{
  width: 100%;
}
}
.dialog-footer{
  width: 100%;
  display: flex;
  justify-content: center;
  .el-button{
    width: 90%;
  }
}
</style>
